import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from './entities/comment.entity';
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { User } from '../user/entities/user.entity';
import { Book } from '../book/entities/book.entity';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(Book)
    private bookRepository: Repository<Book>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async create(createCommentDto: CreateCommentDto, userId: string) {
    // 检查图书是否存在
    const book = await this.bookRepository.findOne({ where: { id: createCommentDto.book_id } });
    if (!book) {
      throw new NotFoundException(`ID为${createCommentDto.book_id}的图书不存在`);
    }

    // 检查用户是否存在
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new NotFoundException(`ID为${userId}的用户不存在`);
    }

    // 创建评论
    const comment = this.commentRepository.create({
      content: createCommentDto.content,
      rating: createCommentDto.rating,
      book_id: createCommentDto.book_id,
      user_id: userId,
      is_visible: createCommentDto.is_visible !== undefined ? createCommentDto.is_visible : true,
    });

    return this.commentRepository.save(comment);
  }

  async findAll() {
    return this.commentRepository.find({
      relations: ['book', 'user'],
      where: { is_visible: true },
      order: { created_at: 'DESC' },
    });
  }

  async findAllByBook(bookId: string) {
    // 检查图书是否存在
    const book = await this.bookRepository.findOne({ where: { id: bookId } });
    if (!book) {
      throw new NotFoundException(`ID为${bookId}的图书不存在`);
    }

    return this.commentRepository.find({
      where: { book_id: bookId, is_visible: true },
      relations: ['user'],
      order: { created_at: 'DESC' },
    });
  }

  async findAllByUser(userId: string) {
    // 检查用户是否存在
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new NotFoundException(`ID为${userId}的用户不存在`);
    }

    return this.commentRepository.find({
      where: { user_id: userId },
      relations: ['book'],
      order: { created_at: 'DESC' },
    });
  }

  async findOne(id: string) {
    const comment = await this.commentRepository.findOne({
      where: { id },
      relations: ['book', 'user'],
    });

    if (!comment) {
      throw new NotFoundException(`ID为${id}的评论不存在`);
    }

    return comment;
  }

  async update(id: string, updateCommentDto: UpdateCommentDto, userId: string, isAdmin: boolean) {
    const comment = await this.commentRepository.findOne({ where: { id } });
    if (!comment) {
      throw new NotFoundException(`ID为${id}的评论不存在`);
    }

    // 只有评论作者或管理员可以更新评论
    if (comment.user_id !== userId && !isAdmin) {
      throw new ForbiddenException('您没有权限更新此评论');
    }

    // 更新评论
    Object.assign(comment, updateCommentDto);
    return this.commentRepository.save(comment);
  }

  async remove(id: string, userId: string, isAdmin: boolean) {
    const comment = await this.commentRepository.findOne({ where: { id } });
    if (!comment) {
      throw new NotFoundException(`ID为${id}的评论不存在`);
    }

    // 只有评论作者或管理员可以删除评论
    if (comment.user_id !== userId && !isAdmin) {
      throw new ForbiddenException('您没有权限删除此评论');
    }

    return this.commentRepository.remove(comment);
  }

  async addSampleComments() {
    // 获取第一本书和第一个用户作为示例
    const book = await this.bookRepository.findOne({ where: {} });
    const user = await this.userRepository.findOne({ where: {} });

    if (!book || !user) {
      throw new NotFoundException('没有找到图书或用户，请先添加图书和用户');
    }

    const sampleComments = [
      {
        content: '这本书非常精彩，强烈推荐！',
        rating: 5,
        book_id: book.id,
        user_id: user.id,
        is_visible: true,
      },
      {
        content: '内容丰富，但有些章节略显冗长。',
        rating: 4,
        book_id: book.id,
        user_id: user.id,
        is_visible: true,
      },
      {
        content: '这本书对我帮助很大，值得一读。',
        rating: 5,
        book_id: book.id,
        user_id: user.id,
        is_visible: true,
      },
    ];

    const comments = this.commentRepository.create(sampleComments);
    return this.commentRepository.save(comments);
  }
}
